// Engine.cpp (c) 2011 JV Software
//

#include "EnginePrivate.h"

Engine	engineLocal;
ENGINE_API Engine	*engine = &engineLocal;

FMemoryManager memoryLocal;
ENGINE_API FMemoryManager *memory = &memoryLocal;

/*
=========
Engine::Init
=========
*/
void Engine::Init(void *hinstance, FString cmdline) {
	engine->Printf(TEXT("---------- Engine::Init -----------\n") );

	// Init the memory manager.
	memory->Init();

	// Init the filesystem.
	fileSystem->Init();

	// Create the game window.
	gameWindow = sys->AllocWindow();
	gameWindow->Init( hinstance, TEXT( "FallenGate" ), TEXT( "FallenGateGameWindow" ), 1024, 768 );

	engine->Printf(TEXT("Game Window Created...\n"));

	// Init the graphics device.
	graphicsDevice->Init( gameWindow );

	// Init the material manager.
	materialManager->Init();

	// Everything is loaded, show the game window.
	gameWindow->Show();

	// Init the session.
	session.Init();

	//engine->Printf(TEXT("Memory Usage %d\n"), memory->MemoryUsage());
}

/*
=========
Engine::Frame
=========
*/
void Engine::Frame() {
	// Clear the screen.
	graphicsDevice->Clear();

	session.Frame();

	// Present everything to the screen.
	graphicsDevice->Present();
}

/*
=========
Engine::Shutdown
=========
*/
void Engine::Shutdown( void ) {
	engine->Printf(TEXT("---------- Engine::Shutdown -----------\n") );

	// Shutdown the system.
	sys->Shutdown();

	// Check to see if we have any unused memory left.
	if(memory->MemoryUsage() != 0) {
		engine->Warning( TEXT("Engine::Shutdown: Not all objects have been freed\n") );
	}
	else {
		engine->Printf(TEXT("All Objects freed successfully. \n"));
	}
}


/*
================
Engine::Printf
================
*/
void Engine::Printf( FString fmt, ... ) {
	int			len; 
	va_list		argptr;
	wchar_t     *msg = (wchar_t *)fmt.c_str();
	static wchar_t	bigBuffer[32000];

	va_start (argptr,msg);
		len = vswprintf (bigBuffer,sizeof(bigBuffer),msg,argptr);
	va_end (argptr);
	OutputDebugString( bigBuffer );
}

/*
================
Engine::Warning
================
*/
void Engine::Warning( FString fmt, ... ) {
	int			len; 
	va_list		argptr;
	wchar_t     *msg = (wchar_t *)fmt.c_str();
	static wchar_t	bigBuffer[32000];

	va_start (argptr,msg);
		len = vswprintf (bigBuffer,sizeof(bigBuffer),msg,argptr);
	va_end (argptr);

	fmt = TEXT("WARNING: ");
	fmt += bigBuffer;
	Printf( fmt );
}

/*
================
Engine::FatalError
================
*/
void Engine::FatalError( FString fmt, ... ) {
	int			len; 
	va_list		argptr;
	wchar_t     *msg = (wchar_t *)fmt.c_str();
	static wchar_t	bigBuffer[32000];

	va_start (argptr,msg);
		len = vswprintf (bigBuffer,sizeof(bigBuffer),msg,argptr);
	va_end (argptr);

	// Print the error to the console.
	fmt = TEXT("Error: ");
	fmt += bigBuffer;
	Printf( fmt );

	sys->FatalError( bigBuffer );
}